import {Component, OnInit, ViewChild} from '@angular/core';
import {adSystemApiUrl, AliyunOssOutputUrl} from '../../../../config/api';
import {HttpService} from '../../../lib/service/http.service';
import {LocalStorageService} from '../../../lib/service/local-storage.service';
import {ModalDirective} from 'ngx-bootstrap';
import {TempManageService} from './temp-manage-service';
import * as moment from 'moment';

export class AddBatchJob {
  job_content = {};
  send_mode = 3;
  wx_id;
  wx_template_message_id;
  applet_id;
  applet_uuid;
  appid;
  send_time;
}

@Component({
  selector: 'app-template',
  templateUrl: 'temp-manage.component.html',
  styleUrls: ['temp-manage.component.scss'],
  providers: [TempManageService]
})

export class TemplateComponent implements OnInit {

  nowApplet;
  aliyunOssOutputUrl = AliyunOssOutputUrl;
  loadingShow = false;
  keyword = '';
  templateList = [];
  allTempList = [];
  operateId;
  id;  // 关键词ID
  key;  // 关键词
  jobList = [];
  keyList = [];
  tabs = 1;
  steps = 0;
  checked_temp;
  keyWord_magnify = '0';
  keyWord_red = 0;
  url_type = 'pages/index/index';
  keyWordDlg: string;
  addBatchJob = new AddBatchJob();

  checkedGoods;
  checkedGroup;
  checkedCoupon;
  groupType = 1;
  groupList = [];
  groupIdDlg = 0;
  statusDlg = '选择商品状态';
  goodsListDlg = [];
  activityList = [];
  sendAttr = 0;
  delay = 0;
  sendDate: string;
  sendTime: string;
  msgContent = [];
  coupon_name;
  cardList = [];

  type: string;
  message: string;
  isShow = false;
  totalItemsDlg = 12;
  itemsPerPageDlg = 4;
  currentPageDlg = 1;
  totalItems: number;
  itemsPerPage = 12;
  currentPage = 1;

  private now = new Date();
  private selDate = 'MM/DD/YYYY';
  minDate = '';
  private maxDate = '';
  private disableDays: Array<number> = [];    // For Sunday and Saturday
  private toContainPrevMonth = false;
  private toContainNextMonth = false;

  @ViewChild('deleteModal') public deleteModal: ModalDirective;
  @ViewChild('addTempModal') public addTempModal: ModalDirective;
  @ViewChild('editTempModal') public editTempModal: ModalDirective;
  @ViewChild('addGoodsModal') public addGoodsModal: ModalDirective;
  @ViewChild('addGroupModal') public addGroupModal: ModalDirective;
  @ViewChild('addCouponModal') public addCouponModal: ModalDirective;

  constructor(private httpService: HttpService,
              private localStorageService: LocalStorageService,
              private tempManageService: TempManageService) {
  }

  ngOnInit() {
    this.nowApplet = this.localStorageService.getNowApplet();
    this.getOwnerTemplateList();
    this.minDate = this.now.getFullYear() + '/' + ((this.now.getMonth() + 1) < 10 ? '0' : '') + (this.now.getMonth() + 1) + "/" + (this.now.getDate() < 10 ? "0" : "") + this.now.getDate();
  }

  newArray = (start, end) => {
    const result = [];
    for (let i = start; i < end; i++) {
      result.push(i);
    }
    return result;
  }
  disabledHours = () => {
    const myDate = new Date();
    const nowHours = myDate.getHours();
    const hours = this.newArray(0, 60);
    // const nowDate = myDate.toLocaleString( );
    // if (nowDate == this.sendDate) {
    hours.splice(nowHours, 4);
    // }
    return hours;
  }
  disabledMinutes = (h) => {
    // if (h === 20) {
    //   return this.newArray(0, 31);
    // } else if (h === 23) {
    //   return this.newArray(30, 60);
    // }
    // return [];
  }

  // 获取拥有的模板消息列表
  getOwnerTemplateList() {
    const url = `${adSystemApiUrl}/v1/member/wechat/applet_message_template_list?page=1&pageSize=999`;
    return this.httpService.httpGetAuth(url).subscribe(
      res => {
        this.templateList = res.data.data;
        if (!!this.templateList) {
          this.templateList.every((val, idx, array) => {
            if (!!val.extend) {
              val.extend.key_list = JSON.parse(val.extend.key_list);
              val.extend.keyword_list = JSON.parse(val.extend.keyword_list);
              return true;
            } else {
              return false;
            }
          });
        }
      }
    );
  }

  getAllTempList(page, pageSize, keyword) {
    this.keyword = keyword;
    if (keyword === '全部') {
      keyword = '';
    }
    this.allTempList = [];
    const url = `${adSystemApiUrl}/v1/member/wechat/admin_message_template_lists?page=${page}&pageSize=${pageSize}&keyword=${keyword}`;
    return this.httpService.httpGetAuth(url).subscribe(
      res => {
        if (res.code === 2000) {
          this.currentPage = res.data.current_page;
          this.totalItems = res.data.total;
          this.allTempList = res.data.data;
          this.allTempList.every((val, idx, array) => {
            val.key_list = JSON.parse(val.key_list);
            val.keyword_list = JSON.parse(val.keyword_list);
            if (!!this.templateList.length) {
              this.templateList.every((val1, idx1, array1) => {
                if (val1.wx_id === val.wx_id) {
                  val.selected = true;
                  val.template_id = val1.template_id;
                  return false;
                } else {
                  return true;
                }
              });
            }
            return true;
          });
          // this.addTempModal.show();
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  checkedCustom() {
    this.tabs = 2;
    // this.getAllTempList(1, this.itemsPerPage, '支付成功');
    this.getJobList();
  }

  // 获取已添加的消息模板列表
  getJobList() {
    this.tempManageService.getJobList(this.currentPage, this.itemsPerPage).subscribe(
      res => {
        this.currentPage = res.data.current_page;
        this.totalItems = res.data.total;
        this.jobList = res.data.data;
        if (!!this.jobList) {
          this.jobList.every((val, idx, array) => {
            const page = JSON.parse(val.job_content).page;
            if (page.indexOf('index') !== -1) {
              val.pageType = '首页';
            }
            if (page.indexOf('pages/product/product?id=') !== -1) {
              val.pageType = '商品详情';
            }
            if (page.indexOf('product-list') !== -1) {
              val.pageType = '商品列表';
            }
            if (page.indexOf('pages/group-product/group-product?id=') !== -1) {
              val.pageType = '拼团详情';
            }
            if (page.indexOf('pages/group-buy-list/group-buy-list?tab=') !== -1) {
              val.pageType = '拼团列表';
            }
            if (page.indexOf('pages/index/index?card_coupons_uuid=') !== -1) {
              val.pageType = '卡券';
            }
            return true;
          });
        }
      }
    );
  }

  addMsgTemp(data) {
    // let canAdd = true;
    // this.allTempList.every((val, idx, array) => {
    //   if (val.selected) {
    //     canAdd = false;
    //     return false;
    //   }
    //   return true;
    // });
    // if (!canAdd) {
    //   this.type = 'info';
    //   this.message = '每一类型下的模板最多只能添加一个';
    //   this.isShow = true;
    //   return;
    // }
    const url = `${adSystemApiUrl}/v1/member/wechat/add_message_template?template_id=${data.id}`;
    return this.httpService.httpPostAuth(url, '').subscribe(
      res => {
        if (res.code === 2000) {
          this.type = 'success';
          this.message = '成功添加消息模板';
          this.isShow = true;
          data.selected = true;
          this.getOwnerTemplateList();
        } else if (res.code === 5000) {
          this.type = 'info';
          this.message = '请先将小程序授权';
          this.isShow = true;
        } else {
          this.type = 'error';
          this.message = res.data.errmsg;
          this.isShow = true;
        }
      }
    );
  }

  delMsgTemp(id) {
    console.log(id);
    const url = `${adSystemApiUrl}/v1/member/wechat/del_message_template?template_id=${id}`;
    return this.httpService.httpPostAuth(url, '').subscribe(
      res => {
        if (res.code === 2000) {
          this.type = 'success';
          this.message = '成功删除消息模板';
          this.isShow = true;
          this.getOwnerTemplateList();
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  // 选中模板
  checkedTemp(item) {
    this.checked_temp = item;
    this.msgContent = [];
    this.addBatchJob.wx_id = item.wx_id;
    this.addBatchJob.appid = item.appid;
    this.addBatchJob.applet_id = item.applet_id;
    this.addBatchJob.applet_uuid = item.applet_uuid;
    this.addBatchJob.wx_template_message_id = item.wx_template_message_id;
  }

  // 下一步
  nextStep(steps) {
    this.steps = steps;
  }

  // 关键词放大
  checkedKeyWord() {
    if (this.keyWord_magnify === '1') {
      this.keyWord_magnify = '0';
    } else {
      this.keyWord_magnify = '1';
    }
  }

  // 关键字标红
  checkedRed() {
    if (!!this.keyWord_red) {
      this.keyWord_red = 0;
    } else {
      this.keyWord_red = 1;
    }
  }

  // 更改链接类型
  changeUrl() {
    if (this.url_type === 'pages/product/product') {
      this.getGroupList();
      this.currentPageDlg = 1;
      this.itemsPerPageDlg = 4;
      this.getDlgGoodsList(1, this.groupIdDlg, this.statusDlg, this.keyWordDlg);
      this.addGoodsModal.show();
    }
    if (this.url_type === 'pages/group-product/group-product') {
      this.getActivityList(1, this.itemsPerPageDlg, '进行中', this.groupType);
      this.currentPageDlg = 1;
      this.itemsPerPageDlg = 4;
      this.addGroupModal.show();
    }
    if (this.url_type === 'pages/index/index?card_coupons_uuid=') {
      this.currentPageDlg = 1;
      this.itemsPerPageDlg = 7;
      this.getCouponList();
      this.addCouponModal.show();
    }
  }

  // 获取商品分组列表
  getGroupList() {
    const url = `${adSystemApiUrl}/v1/member/applet_goods_category/list`;
    return this.httpService.httpGetAuth(url).subscribe(
      res => {
        this.groupList = res.data.data;
      }
    );
  }

  // 添加商品..弹框中的搜索与重置
  searchDlg() {
    this.currentPageDlg = 1;
    if (this.url_type === 'pages/product/product') {
      this.getDlgGoodsList(1, this.groupIdDlg, this.statusDlg, this.keyWordDlg);
    } else {
      this.getCouponList();
    }
  }

  resetDlg() {
    this.keyWordDlg = '';
    this.groupIdDlg = 0;
    this.statusDlg = '选择商品状态';
    this.getDlgGoodsList(1);
  }

  // 获取所有的商品列表，显示在弹框中
  getDlgGoodsList(page: number, applet_goods_category_id?: number, status?: string, keyword?: string, pagesize?: number) {
    const _pageSize = pagesize || 4;
    this.tempManageService.getGoodsList(
      this.nowApplet.applet_uuid,
      page, _pageSize,
      applet_goods_category_id,
      status,
      '',
      keyword
    ).subscribe(
      res => {
        if (res.code === 2000) {
          this.currentPageDlg = res.data.current_page;
          this.totalItemsDlg = res.data.total;
          this.goodsListDlg = res.data.data;
          const ids = [];
          this.goodsListDlg.every((val, idx, array) => {
            ids.push(val.id);
            return true;
          });
          this.tempManageService.getbindListAll(JSON.stringify(ids)).subscribe(
            res1 => {
              this.goodsListDlg.every((val, idx, array) => {
                val.goods_category = [];
                res1.data.every((val1, idx1, array1) => {
                  if (val.id === val1.goods_id) {
                    val.goods_category.push({name: val1.name, id: val1.applet_goods_category_id});
                  }
                  return true;
                });
                return true;
              });
            }
          );
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  changeGroupType(groupType) {
    this.groupType = groupType;
    this.getActivityList(1, this.itemsPerPageDlg, '进行中', this.groupType);
  }

  // 获取活动列表
  getActivityList(page,
                  pageSize,
                  stage,
                  type) {
    this.tempManageService.getActivityList(page, pageSize, stage, type).subscribe(
      res => {
        this.activityList = [];
        if (res.code === 2000) {
          this.currentPageDlg = res.data.current_page;
          this.totalItemsDlg = res.data.total;
          this.activityList = res.data.data;
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  // 获取卡券列表
  getCouponList() {
    this.tempManageService.getCouponList(this.currentPageDlg, this.itemsPerPageDlg, this.coupon_name).subscribe(res => {
      this.totalItemsDlg = res.data.total;
      this.cardList = res.data.data;
      if (!!res.data.data.length) {
        res.data.data.every((val, idx, array) => {
          if (val.in_stock_type === 1 && !!val.card_coupons_used_report) {
            val.remain = val.in_stock - val.card_coupons_used_report.used_total;
          } else {
            val.remain = '不限';
          }
          return true;
        });
      }
    });
  }

  dlgPageChanged(event) {
    if (this.url_type === 'pages/product/product') {
      this.getDlgGoodsList(event.page, this.groupIdDlg, this.statusDlg, this.keyWordDlg);
    } else if (this.url_type === 'pages/group-product/group-product') {
      this.getActivityList(event.page, this.itemsPerPageDlg, '进行中', this.groupType);
    } else {
      this.getCouponList();
    }
  }

  // 确认发送自定义模板
  confirmAddBatchJob() {
    if (this.delay === 1) {
      const nowDate = moment().format('MM/DD/YYYY'),
        nowHours = moment().format('HH');
      // 选择日期为当前日
      if (this.sendDate === nowDate) {
        const setHours = parseInt(this.sendTime.substring(0, 2));
        if (setHours > parseInt(nowHours)) {
          this.addBatchJob.send_time = moment().format('YYYY-MM-DD') + ' ' + this.sendTime + ':00';
        } else if (setHours === parseInt(nowHours)) {
          // 选择小时为当前小时
          const setMinutes = parseInt(this.sendTime.substring(3, 2));
          const nowMinutes = parseInt(moment().format('MM'));
          if (setMinutes - 5 > nowMinutes) {
            this.addBatchJob.send_time = moment().format('YYYY-MM-DD') + this.sendTime + ':00';
          } else {
            this.addBatchJob.send_time = moment().add(5, 'minute').format('YYYY-MM-DD HH:mm:ss');
          }
        } else {
          this.addBatchJob.send_time = moment().add(5, 'minute').format('YYYY-MM-DD HH:mm:ss');
        }
      } else {
        // 选择日期为之后日期
        this.addBatchJob.send_time = this.sendDate.substring(6) + '-' + this.sendDate.substring(0, 2) + '-' + this.sendDate.substring(3, 5) + ' ' + this.sendTime + ':00';
      }
    } else {
      this.addBatchJob.send_time = moment().add(5, 'minute').format('YYYY-MM-DD HH:mm:ss');
    }
    console.log(this.addBatchJob.send_time);
    this.addBatchJob.job_content['emphasis_keyword'] = this.keyWord_magnify;
    const keyword = {};
    this.checked_temp.extend.keyword_list.every((val, idx, array) => {
      keyword['keyword' + (idx + 1)] = this.msgContent[idx];
      return true;
    });
    this.addBatchJob.job_content['keyword'] = keyword;
    let page;
    if (this.url_type === 'pages/product/product') {
      page = 'pages/product/product?id=' + this.checkedGoods.id;
    } else if (this.url_type === 'pages/group-product/group-product') {
      page = 'pages/group-product/group-product?id=' + this.checkedGroup.activity_goods[0].id;
    } else if (this.url_type === 'pages/group-buy-list/group-buy-list') {
      page = 'pages/group-buy-list/group-buy-list?tab=' + this.groupType;
    } else if (this.url_type === 'pages/index/index?card_coupons_uuid=') {
      page = 'pages/index/index?card_coupons_uuid=' + this.checkedCoupon.card_coupons_uuid;
    } else {
      page = this.url_type;
    }
    this.addBatchJob.job_content['page'] = page;
    if (this.keyWord_red) {
      this.addBatchJob.job_content['emphasis_keyword_color'] = '#ef3318';
    } else {
      this.addBatchJob.job_content['emphasis_keyword_color'] = '#000';
    }
    this.addBatchJob.job_content = JSON.stringify(this.addBatchJob.job_content);
    this.tempManageService.postJob(this.addBatchJob).subscribe(
      res => {
        if (res.code === 2000) {
          this.type = 'success';
          this.message = '添加成功';
          this.isShow = true;
          this.steps = 0;
          this.keyWord_magnify = '0';
          this.keyWord_red = 0;
          this.msgContent = [];
          this.checked_temp = {};
          this.addBatchJob.job_content = {};
          this.url_type = 'pages/index/index';
          this.getJobList();
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  pageChanged(event: any): void {
    this.currentPage = event.page;
    if (this.tabs === 1) {
      this.getAllTempList(1, this.itemsPerPage, this.keyword);
    } else {
      this.getJobList();
    }
  }
}
